package com.ishanggang.util.excel;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.ishanggang.entity.ShopQuechao;
import com.ishanggang.mapper.ShopQuechaoMapper;
import com.ishanggang.vo.BrandShopExcelVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;

public class IndexOrNameDataListener extends AnalysisEventListener<BrandShopExcelVo> {
    private static final Logger logger = LoggerFactory.getLogger(IndexOrNameDataListener.class);
    private ShopQuechaoMapper shopQuechaoMapper;
    /**
     * 每隔5条存储数据库，实际使用中可以100条，然后清理list ，方便内存回收
     */
    private static final int BATCH_COUNT = 1000;
    private List<BrandShopExcelVo> cachedDataList = new ArrayList<>();

    public IndexOrNameDataListener(ShopQuechaoMapper shopQuechaoMapper) {
        this.shopQuechaoMapper = shopQuechaoMapper;
    }

    @Override
    public void invoke(BrandShopExcelVo data, AnalysisContext context) {
//        logger.info("解析到一条数据:{}", JSON.toJSONString(data));
        cachedDataList.add(data);
        if (cachedDataList.size() >= BATCH_COUNT) {
            saveData();
            cachedDataList = new ArrayList<>();
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        saveData();
        logger.info("所有数据解析完成！");
    }

    /**
     * 加上存储数据库
     */
    private void saveData() {
        logger.info("{}条数据，开始存储数据库！", cachedDataList.size());
//        for(BrandShopExcelVo brandShopExcelVo:cachedDataList){
//            logger.info("{}", brandShopExcelVo);
//        }
        int num = shopQuechaoMapper.batchInsert(cachedDataList);
        logger.info("{}存储数据库成功！", num);
    }
}